package com.wephone.Student.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.wephone.Student.R;
import com.wephone.Student.bean.CarInfoResponse;
import com.wephone.Student.bean.data.CarInfoData;
import com.wephone.Student.bean.data.MyLocationInfo;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.PullToRefreshView;
import com.wephone.Student.util.PullToRefreshView.OnFooterRefreshListener;
import com.wephone.Student.util.PullToRefreshView.OnHeaderRefreshListener;

public class MutualTransactionList2Activity extends BaseActivity {
	private PullToRefreshView pullToRefreshListView;
	private ListView listView;
	private ListViewAdapter adapter;
	private List<CarInfoData> results = new ArrayList<CarInfoData>();
	private String cLoc;
	private String cTitle;
	private String cType;
	
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(MutualTransactionList2Activity.this,CarInfoResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					CarInfoResponse res = (CarInfoResponse)response;
					
					if(adapter.pageIdx>=res.getTotalPage() || res.getData().size()<Constants.PAGE_SIZE){
						adapter.hasMore = false;
					}else{
						adapter.pageIdx++;
					}
					results.addAll(res.getData());
					adapter.notifyDataSetChanged();
				}
			}
		};
		return handler;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==11 && resultCode==111){
			findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
			cLoc = data.getStringExtra("cLoc");
			cTitle = data.getStringExtra("cTitle");
			cType = data.getStringExtra("cType");
			
			results.clear();
			adapter.notifyDataSetChanged();
			adapter.pageIdx = 1;
			adapter.hasMore = true;
			
			RequestParams params = new RequestParams();
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			if(!TextUtils.isEmpty(cLoc)){
				params.put("cLoc", cLoc);
			}
			if(!TextUtils.isEmpty(cTitle)){
				params.put("cTitle", cTitle);
			}
			if(!TextUtils.isEmpty(cType)){
				params.put("cType", cType);
			}
			params.put("cCarType", "");
			HttpClient.getInstance().get(Constants.API_GET_CAR_INFO_LIST_URL, params, getHandler());
		}else if(requestCode==22 && resultCode==222){
			findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
			results.clear();
			adapter.notifyDataSetChanged();
			adapter.pageIdx = 1;
			adapter.hasMore = true;
			
			RequestParams params = new RequestParams();
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			if(!TextUtils.isEmpty(cLoc)){
				params.put("cLoc", cLoc);
			}
			HttpClient.getInstance().get(Constants.API_GET_CAR_INFO_LIST_URL, params, getHandler());
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mutual_transaction_list_2);
		
		init();
	}
	
	private void init(){
		listView = (ListView)findViewById(R.id.listview);
		adapter = new ListViewAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				MutualTransaction2DetailActivity.data = results.get(arg2);
				startActivity(new Intent(getApplicationContext(),MutualTransaction2DetailActivity.class));
			}});
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		findViewById(R.id.btn_top_right_1).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(getApplicationContext(),CreateMutualTransaction2Activity.class),22);
			}
		});
		findViewById(R.id.btn_top_right_2).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),MutualTransactionSearch2Activity.class);
				intent.putExtra("searchDefaultCountry", cLoc);
				startActivityForResult(intent,11);
			}
		});
		pullToRefreshListView = (PullToRefreshView)findViewById(R.id.pull_refresh_listview);
		pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
			@Override
			public void onHeaderRefresh(PullToRefreshView view) {
				results.clear();
				adapter.hasMore = true;
				adapter.pageIdx = 1;
				
				RequestParams params = new RequestParams();
				params.put("Page", "1");
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				Gson gson = new Gson();
				MyLocationInfo locInfo = gson.fromJson(BaseActivity.getMyInfo(getApplicationContext()).getuLocDetail(), MyLocationInfo.class);
				if(locInfo.getType().equals("PlanGoOut")){
					if(!TextUtils.isEmpty(locInfo.getTocountry())){
						cLoc = locInfo.getTocountry();
						params.put("cLoc", cLoc);
					}
				}else if(locInfo.getType().equals("Returnees")){
					if(!TextUtils.isEmpty(locInfo.getCountry())){
						cLoc = locInfo.getCountry();
						params.put("cLoc", cLoc);
					}
				}else{
					if(!TextUtils.isEmpty(locInfo.getCountry())){
						cLoc = locInfo.getCountry();
						params.put("cLoc", cLoc);
					}
				}
				HttpClient.getInstance().get(Constants.API_GET_CAR_INFO_LIST_URL, params, getHandler());
			}
		});
		pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
			@Override
			public void onFooterRefresh(PullToRefreshView view) {
				if(!adapter.hasMore){
					pullToRefreshListView.onFooterRefreshComplete();
					return;
				}
				RequestParams params = new RequestParams();
				params.put("Page", ""+adapter.pageIdx);
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				if(!TextUtils.isEmpty(cLoc)){
					params.put("cLoc", cLoc);
				}
				if(!TextUtils.isEmpty(cTitle)){
					params.put("cTitle", cTitle);
				}
				if(!TextUtils.isEmpty(cType)){
					params.put("cType", cType);
				}
				params.put("cCarType", "");
				HttpClient.getInstance().get(Constants.API_GET_CAR_INFO_LIST_URL, params, getHandler());
			}
		});
		
		RequestParams params = new RequestParams();
		params.put("Page", "1");
		params.put("PageSize", ""+Constants.PAGE_SIZE);
		Gson gson = new Gson();
		MyLocationInfo locInfo = gson.fromJson(BaseActivity.getMyInfo(getApplicationContext()).getuLocDetail(), MyLocationInfo.class);
		if(locInfo.getType().equals("PlanGoOut")){
			if(!TextUtils.isEmpty(locInfo.getTocountry())){
				cLoc = locInfo.getTocountry();
				params.put("cLoc", cLoc);
			}
		}else if(locInfo.getType().equals("Returnees")){
			if(!TextUtils.isEmpty(locInfo.getCountry())){
				cLoc = locInfo.getCountry();
				params.put("cLoc", cLoc);
			}
		}else{
			if(!TextUtils.isEmpty(locInfo.getCountry())){
				cLoc = locInfo.getCountry();
				params.put("cLoc", cLoc);
			}
		}
		HttpClient.getInstance().get(Constants.API_GET_CAR_INFO_LIST_URL, params, getHandler());
	}
	
	private class ListViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		
		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.include_mutual_transaction_2_list_item, null);
			}
			CarInfoData flyInfo = results.get(position);
			TextView itemName = (TextView)convertView.findViewById(R.id.item_name);
			itemName.setText(flyInfo.getcTitle());
			TextView itemCountry = (TextView)convertView.findViewById(R.id.item_country);
			if(TextUtils.isEmpty(flyInfo.getcPrice()) || Double.parseDouble(flyInfo.getcPrice())<=0){
				itemCountry.setText("面议");
			}else{
				itemCountry.setText(flyInfo.getcPrice());
			}
			TextView flyDate = (TextView)convertView.findViewById(R.id.item_fly_date);
			flyDate.setText(sdf.format(new Date(Long.parseLong(flyInfo.getcTs())*1000)));
			TextView itemSign = (TextView)convertView.findViewById(R.id.item_signature);
			itemSign.setText(flyInfo.getcDetail());
			
			ImageView itemImage = (ImageView)convertView.findViewById(R.id.item_image);
			DisplayImageOptions options = new DisplayImageOptions.Builder()
	        .showStubImage(R.drawable.default_user_logo)
	        .showImageOnFail(R.drawable.default_user_logo)
	        .bitmapConfig(Bitmap.Config.ARGB_8888)
	        .cacheInMemory()
	        .cacheOnDisc()
	        .displayer(new RoundedBitmapDisplayer(10))
	        .build();
//			if(!TextUtils.isEmpty(flyInfo.getcImg1())){
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getcImg1(), itemImage, options);
//				String endStr = flyInfo.getcImg1().substring(flyInfo.getcImg1().lastIndexOf("."));
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getcImg1().replace(endStr, "_150_150"+endStr), itemImage, options);
//			}else if(!TextUtils.isEmpty(flyInfo.getcImg2())){
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getcImg2(), itemImage, options);
//				String endStr = flyInfo.getcImg2().substring(flyInfo.getcImg2().lastIndexOf("."));
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getcImg2().replace(endStr, "_150_150"+endStr), itemImage, options);
//			}else if(!TextUtils.isEmpty(flyInfo.getcImg3())){
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getcImg3(), itemImage, options);
//				String endStr = flyInfo.getcImg3().substring(flyInfo.getcImg3().lastIndexOf("."));
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getcImg3().replace(endStr, "_150_150"+endStr), itemImage, options);
			if(!TextUtils.isEmpty(flyInfo.getuInfo().getuIcon())){
//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getuInfo().getuIcon(), itemImage, options);
				String endStr = flyInfo.getuInfo().getuIcon().substring(flyInfo.getuInfo().getuIcon().lastIndexOf("."));
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+flyInfo.getuInfo().getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
			}else{
				itemImage.setImageResource(R.drawable.default_user_logo);
			}
			
////			load more
//			if(position>=results.size()-1 && hasMore){
//				RequestParams params = new RequestParams();
//				params.put("Page", ""+pageIdx);
//				params.put("PageSize", ""+Constants.PAGE_SIZE);
//				if(!TextUtils.isEmpty(cLoc)){
//					params.put("cLoc", cLoc);
//				}
//				if(!TextUtils.isEmpty(cTitle)){
//					params.put("cTitle", cTitle);
//				}
//				if(!TextUtils.isEmpty(cType)){
//					params.put("cType", cType);
//				}
//				params.put("cCarType", "");
//				HttpClient.getInstance().get(Constants.API_GET_CAR_INFO_LIST_URL, params, getHandler());
//			}
			return convertView;
		}		
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        menu.add("刷新");
        return super.onCreateOptionsMenu(menu);
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if(item.getItemId() == 0){
            findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
            
            adapter.pageIdx = 1;
            adapter.hasMore = true;
            results.clear();
			adapter.notifyDataSetChanged();
			
			cTitle = "";
			cType = "";
			Gson gson = new Gson();
			MyLocationInfo locInfo = gson.fromJson(BaseActivity.getMyInfo(getApplicationContext()).getuLocDetail(), MyLocationInfo.class);
			if(locInfo.getType().equals("PlanGoOut")){
				if(!TextUtils.isEmpty(locInfo.getTocountry())){
					cLoc = locInfo.getTocountry();
				}
			}else if(locInfo.getType().equals("Returnees")){
				if(!TextUtils.isEmpty(locInfo.getCountry())){
					cLoc = locInfo.getCountry();
				}
			}else{
				if(!TextUtils.isEmpty(locInfo.getCountry())){
					cLoc = locInfo.getCountry();
				}
			}
    		
    		RequestParams params = new RequestParams();
    		params.put("Page", "1");
    		params.put("PageSize", ""+Constants.PAGE_SIZE);
    		if(!TextUtils.isEmpty(cLoc)){
				params.put("cLoc", cLoc);
			}
    		HttpClient.getInstance().get(Constants.API_GET_CAR_INFO_LIST_URL, params, getHandler());
        } 
        return true;
    }
	
}
